1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect;
18  
19  import static com.google.common.base.Preconditions.checkNotNull;
20  
21  import com.google.common.annotations.GwtCompatible;
22  import com.google.common.annotations.GwtIncompatible;
23  
24  import java.io.IOException;
25  import java.io.ObjectInputStream;
26  import java.io.ObjectOutputStream;
27  import java.util.EnumMap;
28  import java.util.HashMap;
29  import java.util.Map;
30  
31  import javax.annotation.Nullable;
32  
33  /**
34   * A {@code BiMap} backed by an {@code EnumMap} instance for keys-to-values, and
35   * a {@code HashMap} instance for values-to-keys. Null keys are not permitted,
36   * but null values are. An {@code EnumHashBiMap} and its inverse are both
37   * serializable.
38   * 
39   * <p>See the Guava User Guide article on <a href=
40   * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap">
41   * {@code BiMap}</a>.
42   *
43   * @author Mike Bostock
44   * @since 2.0 (imported from Google Collections Library)
45   */
46  @GwtCompatible(emulated = true)
47  public final class EnumHashBiMap<K extends Enum<K>, V>
48      extends AbstractBiMap<K, V> {
49    private transient Class<K> keyType;
50  
51    /**
52     * Returns a new, empty {@code EnumHashBiMap} using the specified key type.
53     *
54     * @param keyType the key type
55     */
56    public static <K extends Enum<K>, V> EnumHashBiMap<K, V>
57        create(Class<K> keyType) {
58      return new EnumHashBiMap<K, V>(keyType);
59    }
60  
61    /**
62     * Constructs a new bimap with the same mappings as the specified map. If the
63     * specified map is an {@code EnumHashBiMap} or an {@link EnumBiMap}, the new
64     * bimap has the same key type as the input bimap. Otherwise, the specified
65     * map must contain at least one mapping, in order to determine the key type.
66     *
67     * @param map the map whose mappings are to be placed in this map
68     * @throws IllegalArgumentException if map is not an {@code EnumBiMap} or an
69     *     {@code EnumHashBiMap} instance and contains no mappings
70     */
71    public static <K extends Enum<K>, V> EnumHashBiMap<K, V>
72        create(Map<K, ? extends V> map) {
73      EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyType(map));
74      bimap.putAll(map);
75      return bimap;
76    }
77  
78    private EnumHashBiMap(Class<K> keyType) {
79      super(WellBehavedMap.wrap(
80          new EnumMap<K, V>(keyType)),
81          Maps.<V, K>newHashMapWithExpectedSize(
82              keyType.getEnumConstants().length));
83      this.keyType = keyType;
84    }
85  
86    // Overriding these 3 methods to show that values may be null (but not keys)
87  
88    @Override
89    K checkKey(K key) {
90      return checkNotNull(key);
91    }
92  
93    @Override public V put(K key, @Nullable V value) {
94      return super.put(key, value);
95    }
96  
97    @Override public V forcePut(K key, @Nullable V value) {
98      return super.forcePut(key, value);
99    }
100 
101   /** Returns the associated key type. */
102   public Class<K> keyType() {
103     return keyType;
104   }
105 
106   /**
107    * @serialData the key class, number of entries, first key, first value,
108    *     second key, second value, and so on.
109    */
110   @GwtIncompatible("java.io.ObjectOutputStream")
111   private void writeObject(ObjectOutputStream stream) throws IOException {
112     stream.defaultWriteObject();
113     stream.writeObject(keyType);
114     Serialization.writeMap(this, stream);
115   }
116 
117   @SuppressWarnings("unchecked") // reading field populated by writeObject
118   @GwtIncompatible("java.io.ObjectInputStream")
119   private void readObject(ObjectInputStream stream)
120       throws IOException, ClassNotFoundException {
121     stream.defaultReadObject();
122     keyType = (Class<K>) stream.readObject();
123     setDelegates(WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
124         new HashMap<V, K>(keyType.getEnumConstants().length * 3 / 2));
125     Serialization.populateMap(this, stream);
126   }
127 
128   @GwtIncompatible("only needed in emulated source.")
129   private static final long serialVersionUID = 0;
130 }